package com.dlz.systemshop.controller;

import com.dlz.systemshop.pojo.GoodsAlbum;
import com.dlz.systemshop.service.GoodsAlbumService;
import com.dlz.systemshop.utils.ServerAddressUtil;
import jakarta.annotation.PostConstruct;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.NullValueInNestedPathException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@Slf4j
@RestController
@RequestMapping("/goodsAlbum")
public class GoodsAlbumController {
    @Autowired
    private GoodsAlbumService goodsAlbumService;

    // 保存
    @RequestMapping("/saveList")
    public Boolean saveList(@RequestBody List<GoodsAlbum> goodsAlbumList, Integer goodsId) {
        log.info("保存商品图片列表： saveList {} 商品id: {}" , goodsAlbumList.toString() , goodsId);
        if (goodsId == null) goodsId = getGoodsId(goodsAlbumList);
        Assert.notNull(goodsId, "goodsId和 List中的goodsId都为空！");
        // 将所有的 goodsAlbum 的 goodsId 设置为和 goodsId 相同
        setGoodsIdOfList(goodsAlbumList, goodsId);
        Boolean flag = goodsAlbumService.savePicList(goodsAlbumList, goodsId);
        return flag;
    }

    private void setGoodsIdOfList(List<GoodsAlbum> goodsAlbumList, Integer goodsId) {
        goodsAlbumList.forEach((e) -> e.setGoodsId(goodsId));
    }

    // 获取列表
    @RequestMapping("/getListByGoodsId")
    public List<GoodsAlbum> getListByGoodsId(Integer goodsId, HttpServletRequest request) {
        log.info("获取商品图片列表 goodsId " + goodsId);
        Assert.notNull(goodsId, "商品Id不能为空");
        List<GoodsAlbum> list = goodsAlbumService.getListByGoodsId(goodsId);
        String path = ServerAddressUtil.getURLExURI(request);
        list.forEach((e) -> e.setPicture(path + e.getPicture()));
        return list;
    }



    // 默认都是一样的
    private static Integer getGoodsId(List<GoodsAlbum> goodsAlbumList) {
        Integer id = null;
        for (GoodsAlbum goodsAlbum : goodsAlbumList) {
            if (goodsAlbum.getGoodsId() != null) return goodsAlbum.getGoodsId();
        }
        return id;
    }

}
